package cn.lzm.serializer;

import lombok.SneakyThrows;

import java.io.*;

/**
 * @author lzm
 * @Date 2024/7/16
 * @description
 */
public class JDKSerializer implements Serializer {

    @Override
    public <T> byte[] serialize(T data) {
        try (ByteArrayOutputStream os = new ByteArrayOutputStream(); // 完全可以将这个流看做是new File()
             ObjectOutputStream oos = new ObjectOutputStream(os)) {
            oos.writeObject(data);
            return os.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @SneakyThrows
    @Override
    @SuppressWarnings("all")
    public <T> T deserialize(byte[] data, Class<T> clazz) {
        try (ByteArrayInputStream bis = new ByteArrayInputStream(data); ObjectInputStream ois = new ObjectInputStream(bis)) {
            Object obj = ois.readObject();
            return (T) obj;
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }


}
